import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { trpc } from '../utils/trpc'
import { useToast } from 'vue-toastification'
import type { User } from './auth'

// 创建子管理员请求类型
export interface CreateSubAdminRequest {
  email: string
  username: string
  password: string
}

// 创建普通用户请求类型
export interface CreateCustomerRequest {
  email: string
  username: string
  password: string
}

// 更新用户请求类型
export interface UpdateUserRequest {
  userId: number
  email?: string
  username?: string
  isActive?: boolean
  role?: 'ADMIN' | 'SUB_ADMIN' | 'USER'
}

// 用户列表响应类型
export interface UsersResponse {
  users: User[]
  total: number
  page: number
  totalPages: number
}

// 系统统计类型
export interface SystemStats {
  totalUsers: number
  totalAdmins: number
  totalSubAdmins: number
  activeUsers: number
  totalRechargeRecords: number
  totalRechargeAmount: string
}

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const users = ref<User[]>([])
  const subAdmins = ref<User[]>([])
  const systemStats = ref<SystemStats | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 分页状态
  const currentPage = ref(1)
  const totalPages = ref(1)
  const totalUsers = ref(0)

  // 计算属性
  const hasUsers = computed(() => users.value.length > 0)
  const hasSubAdmins = computed(() => subAdmins.value.length > 0)

  // Toast通知
  const toast = useToast()

  // 创建子管理员
  async function createSubAdmin(data: CreateSubAdminRequest) {
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.createSubAdmin.mutate(data)
      
      if (result.success && result.data) {
        subAdmins.value.push(result.data)
        toast.success(result.message || 'Sub-admin created successfully')
        return result.data
      } else {
        throw new Error(result.message || 'Failed to create sub-admin')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to create sub-admin'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 创建普通用户（客户）
  async function createCustomer(data: CreateCustomerRequest) {
    isLoading.value = true
    error.value = null

    try {
      const result = await trpc.admin.createCustomer.mutate(data)

      if (result.success && result.data) {
        // 添加到用户列表
        users.value.unshift(result.data)
        totalUsers.value += 1
        // 不在store中显示成功提示，让调用方控制
        return result.data
      } else {
        throw new Error(result.message || 'Failed to create customer')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to create customer'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取所有用户
  async function getAllUsers(page: number = 1, limit: number = 20) {
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.getAllUsers.query({ page, limit })
      
      if (result.success && result.data) {
        users.value = result.data.users
        currentPage.value = result.data.page
        totalPages.value = result.data.totalPages
        totalUsers.value = result.data.total
        return result.data
      } else {
        throw new Error(result.message || 'Failed to get users')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to get users'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取子管理员列表
  async function getSubAdmins() {
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.getSubAdmins.query()
      
      if (result.success && result.data) {
        subAdmins.value = result.data
        return result.data
      } else {
        throw new Error(result.message || 'Failed to get sub-admins')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to get sub-admins'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 更新用户
  async function updateUser(data: UpdateUserRequest) {
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.updateUser.mutate(data)
      
      if (result.success && result.data) {
        // 更新本地用户列表
        const index = users.value.findIndex(u => u.id === data.userId)
        if (index !== -1) {
          users.value[index] = result.data
        }
        
        // 如果是子管理员，也更新子管理员列表
        const subAdminIndex = subAdmins.value.findIndex(u => u.id === data.userId)
        if (subAdminIndex !== -1) {
          subAdmins.value[subAdminIndex] = result.data
        }
        
        // 不在store中显示成功提示，让调用方控制
        return result.data
      } else {
        throw new Error(result.message || 'Failed to update user')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to update user'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 删除用户
  async function deleteUser(userId: number) {
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.deleteUser.mutate({ userId })
      
      if (result.success) {
        // 从本地列表中移除用户
        users.value = users.value.filter(u => u.id !== userId)
        subAdmins.value = subAdmins.value.filter(u => u.id !== userId)

        // 不在store中显示成功提示，让调用方控制
        return true
      } else {
        throw new Error(result.message || 'Failed to delete user')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to delete user'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 获取系统统计
  async function getSystemStats() {
    // 检查当前路由，如果是公开路由则不执行
    if (typeof window !== 'undefined') {
      const currentPath = window.location.pathname
      if (currentPath.includes('/user-recharge/')) {
        console.log('Skipping admin stats on user recharge page')
        return null
      }
    }
    
    isLoading.value = true
    error.value = null
    
    try {
      const result = await trpc.admin.getSystemStats.query()
      
      if (result.success && result.data) {
        systemStats.value = result.data
        return result.data
      } else {
        throw new Error(result.message || 'Failed to get system stats')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to get system stats'
      toast.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 检查管理员权限
  async function checkAdminPermission() {
    try {
      const result = await trpc.admin.checkAdminPermission.query()
      
      if (result.success && result.data) {
        return result.data
      } else {
        throw new Error(result.message || 'Failed to check permissions')
      }
    } catch (err: any) {
      error.value = err.message || 'Failed to check permissions'
      throw err
    }
  }

  // 清除错误
  function clearError() {
    error.value = null
  }

  // 重置状态
  function resetState() {
    users.value = []
    subAdmins.value = []
    systemStats.value = null
    currentPage.value = 1
    totalPages.value = 1
    totalUsers.value = 0
    error.value = null
  }

  return {
    // 状态
    users,
    subAdmins,
    systemStats,
    isLoading,
    error,
    currentPage,
    totalPages,
    totalUsers,
    hasUsers,
    hasSubAdmins,
    
    // 方法
    createSubAdmin,
    createCustomer,
    getAllUsers,
    getSubAdmins,
    updateUser,
    deleteUser,
    getSystemStats,
    checkAdminPermission,
    clearError,
    resetState,
  }
})
